package com.example.chatroom.common.utils;


import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;



public class JacksonUtil {
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 单例模式
     */
    private final static ObjectMapper OBJECT_MAPPER;

    private JacksonUtil() {}

    static{
        OBJECT_MAPPER=new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    /**
     * 处理 try-catch冗余的问题
     * @param parser
     * @param check
     * @return
     * @param <T>
     */
    private static final <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            } else {
                ReflectionUtils.rethrowRuntimeException(var4);
                throw new IllegalStateException(var4);
            }
        }
    }
    /**
     * 进一步封装，check 可能的异常只有JSONException.class 因为我们只序列号为JSON字符串
     */
    private static final <T> T tryParse(Callable<T> parser){
        return tryParse(parser,JsonParseException.class);
    }

    /**
     * 序列化
     * @param object 待序列化数据
     * @return
     */
    public static String writeValueAsString(Object object){
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().writeValueAsString(object);
        });
    }

    /**
     * 反序列化 java对象
     * @param content
     * @param valueType
     * @return
     * @param <T>
     */
    public static <T> T readValue(String content, Class<T> valueType){
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(content,valueType);
        },JsonParseException.class);
    }

    public static <T> List<T> readListValue(String content, Class<T> paramClasses){
        JavaType javaType=JacksonUtil.getObjectMapper().getTypeFactory().constructParametricType(List.class,paramClasses);
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(content,javaType);
        });
    }
}
